﻿using System;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace ZYB_S007_串口调试器
{
    public partial class From_TCP : Form
    {
        System.Threading.Thread listenerThread;
        System.Net.Sockets.TcpListener listener;

        public From_TCP()
        {
            InitializeComponent();

            //居右显示
            int SH = Screen.PrimaryScreen.Bounds.Height; //1080
            int SW = Screen.PrimaryScreen.Bounds.Width; //1920
            this.Location = new System.Drawing.Point(SW - this.Width - 50, SH / 2 - this.Height / 2);

        }
        Config_Json_Tcp_Server config_server = Config_Json_Tcp_Server.ReadAll();
        Config_Json_Tcp_Client config_client = Config_Json_Tcp_Client.ReadAll();

        private void From_TCP_Load(object sender, EventArgs e)
        {
            restore_config();
        }

        private void restore_config()
        {
            //服务端
            tb_server_port.Text = config_server.server_port;
            tb_指令1.Text = config_server.指令1;
            tb_指令2.Text = config_server.指令2;
            tb_指令3.Text = config_server.指令3;
            tb_指令4.Text = config_server.指令4;
            tb_指令5.Text = config_server.指令5;
            tb_指令6.Text = config_server.指令6;
            tb_指令7.Text = config_server.指令7;
            tb_指令8.Text = config_server.指令8;
            tb_指令9.Text = config_server.指令9;
            tb_指令10.Text = config_server.指令10;

            tb_用途1.Text = config_server.用途1;
            tb_用途2.Text = config_server.用途2;
            tb_用途3.Text = config_server.用途3;
            tb_用途4.Text = config_server.用途4;
            tb_用途5.Text = config_server.用途5;
            tb_用途6.Text = config_server.用途6;
            tb_用途7.Text = config_server.用途7;
            tb_用途8.Text = config_server.用途8;
            tb_用途9.Text = config_server.用途9;
            tb_用途10.Text = config_server.用途10;

            //客户端 
            tb_server_ip.Text = config_client.server_ip;
            tb_客户端port.Text = config_client.server_port;
            tb_客户端指令1.Text = config_client.指令1;
            tb_客户端指令2.Text = config_client.指令2;
            tb_客户端指令3.Text = config_client.指令3;
            tb_客户端指令4.Text = config_client.指令4;
            tb_客户端指令5.Text = config_client.指令5;
            tb_客户端指令6.Text = config_client.指令6;
            tb_客户端指令7.Text = config_client.指令7;
            tb_客户端指令8.Text = config_client.指令8;
            tb_客户端指令9.Text = config_client.指令9;
            tb_客户端指令10.Text = config_client.指令10;

            tb_客户端用途1.Text = config_client.用途1;
            tb_客户端用途2.Text = config_client.用途2;
            tb_客户端用途3.Text = config_client.用途3;
            tb_客户端用途4.Text = config_client.用途4;
            tb_客户端用途5.Text = config_client.用途5;
            tb_客户端用途6.Text = config_client.用途6;
            tb_客户端用途7.Text = config_client.用途7;
            tb_客户端用途8.Text = config_client.用途8;
            tb_客户端用途9.Text = config_client.用途9;
            tb_客户端用途10.Text = config_client.用途10;
        }

        private void btn_server_start_Click(object sender, EventArgs e)
        {
            listenerThread = new System.Threading.Thread(new System.Threading.ThreadStart(start_tcp_server));                     //实例化线程
            listenerThread.IsBackground = true;
            listenerThread.Start();
            lb_server_status.Text = "已启动";
        }
        System.Net.Sockets.TcpListener tcp_server = null;
        System.Net.Sockets.TcpClient tcp_client = null;
        public static System.Collections.Generic.List<TcpClient> clientList = new System.Collections.Generic.List<TcpClient>();
        NetworkStream stream = null;
        /// <summary>
        /// todo tcp server 处理接收到的数据
        /// </summary>
        void start_tcp_server()
        {
            try
            {
                tcp_server = new TcpListener(System.Net.IPAddress.Any,Convert.ToInt16(tb_server_port.Text));
                tcp_server.Start();
               
                string data = null;
                while (true)
                {
                    addmemo_server("服务端已启动,端口号："+tb_server_port.Text);
                    addmemo_server("等待客户端连接...");
                    tcp_client = tcp_server.AcceptTcpClient();
                    addmemo_server("客户端已连接!");
                    data = null;
                    stream = tcp_client.GetStream();
                    int i;
                    try
                    {
                        while (true)
                        {
                            Byte[] bytes = new Byte[256];
                            if ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                            {
                                data = System.Text.Encoding.Default.GetString(bytes);
                                data = data.TrimEnd('\0');
                                addmemo_server("接收：" + data);
                            }

                        }
                    }
                    catch (Exception)
                    {
                        addmemo_server("客户端已断开");
                        tcp_client.Close();
                    }
                    
                  
                }
            }
            catch (SocketException er)
            {
                addmemo_server("socket Exception:" + er.Message);
            }
            finally
            {
                tcp_server.Stop();
            }
        }
        
        void tcp_send_string(string str)
        {
            addmemo_server("发送：" + str);
            byte[] data = new byte[1024];
            stream.Write(Encoding.Default.GetBytes(str), 0, Encoding.ASCII.GetBytes(str).Length);
        }

        private void btn_Server_Stop_Click(object sender, EventArgs e)
        {
           if (listenerThread!=null)
                this.Invoke(new Action(() =>
                {
                    listenerThread.Abort();
                }), null);
            addmemo_server("已停止");

        }

        private void addmemo_server(string memo)
        {
            this.Invoke(new Action(() =>
            {

                tb_server_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + memo + "\r\n");
                tb_server_log.ScrollToCaret();
            }), null);
            try
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter("logs/tcp_server_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", true))
                {
                    writer.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + memo + "\r\n");
                    writer.Close();
                }
            }
            catch { }

        }

        
        private void addmemo_client(string memo)
        {
            this.Invoke(new Action(() =>
            {

                tb_client_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + memo + "\r\n");
                tb_client_log.ScrollToCaret();
            }), null);
            try
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter("logs/tcp_client_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", true))
                {
                    writer.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " " + memo + "\r\n");
                    writer.Close();
                }
            }
            catch { }

        }

        private void btn_发送1_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令1.Text);
        }

        private void btn_发送2_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令2.Text);
        }

        private void btn_发送3_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令3.Text);
        }

        private void btn_发送4_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令4.Text);
        }

        private void btn_发送5_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令5.Text);
        }

        private void btn_发送6_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令6.Text);
        }

        private void btn_发送7_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令7.Text);
        }

        private void btn_发送8_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令8.Text);
        }

        private void button11_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令9.Text);
        }

        private void button10_Click(object sender, EventArgs e)
        {
            tcp_send_string(tb_指令10.Text);
        }

        void 客户端发送(string content)
        {
            byte[] bytes = new byte[8192];
            bytes = Encoding.Default.GetBytes(content);   //将文本转换成字节

            try
            {
                if (clientSocket.Connected)                                                                  //如果连接远程主机
                {
                    clientSocket.Send(bytes);                                                                     //发送数据
                    addmemo_client("发送：" + content);                                                    //显示文本
                }
            }
            catch (Exception ex)
            {
                addmemo_client("出错：" + ex.Message);
            }
          
        }
        private void btn_客户端发送1_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令1.Text);
        }


        private void btn_客户端发送2_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令2.Text);
        }

        private void btn_客户端发送3_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令3.Text);
        }

        private void btn_客户端发送4_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令4.Text);
        }

        private void btn_客户端发送5_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令5.Text);

        }

        private void btn_客户端发送6_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令6.Text);
        }

        private void btn_客户端发送7_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令7.Text);
        }

        private void btn_客户端发送8_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令8.Text);
        }

        private void btn_客户端发送9_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令9.Text);
        }

        private void btn_客户端发送10_Click(object sender, EventArgs e)
        {
            客户端发送(tb_客户端指令10.Text);
        }

        private void btn_客户端保存_Click(object sender, EventArgs e)
        {
            config_client.server_ip = tb_server_ip.Text;
            config_client.server_port = tb_客户端port.Text;
            config_client.指令1 = tb_客户端指令1.Text;
            config_client.指令2 = tb_客户端指令2.Text;
            config_client.指令3 = tb_客户端指令3.Text;
            config_client.指令4 = tb_客户端指令4.Text;
            config_client.指令5 = tb_客户端指令5.Text;
            config_client.指令6 = tb_客户端指令6.Text;
            config_client.指令7 = tb_客户端指令7.Text;
            config_client.指令8 = tb_客户端指令8.Text;
            config_client.指令9 = tb_客户端指令9.Text;
            config_client.指令10 = tb_客户端指令10.Text;
            config_client.用途1 = tb_客户端用途1.Text;
            config_client.用途2 = tb_客户端用途2.Text;
            config_client.用途3 = tb_客户端用途3.Text;
            config_client.用途4 = tb_客户端用途4.Text;
            config_client.用途5 = tb_客户端用途5.Text;
            config_client.用途6 = tb_客户端用途6.Text;
            config_client.用途7 = tb_客户端用途7.Text;
            config_client.用途8 = tb_客户端用途8.Text;
            config_client.用途9 = tb_客户端用途9.Text;
            config_client.用途10 = tb_客户端用途10.Text;

            Config_Json_Tcp_Client.save(config_client);
            MessageBox.Show("保存成功!");
        }
        TcpClient client;
        Socket clientSocket;
        private void btn_客户端连接_Click(object sender, EventArgs e)
        {
            client = new TcpClient(tb_server_ip.Text, Convert.ToInt32(tb_客户端port.Text));  //实例化TcpClient，连接指定主机上的端口

            clientSocket = client.Client;                                                    //获得套接字

            addmemo_client("连接服务端："+ tb_server_ip.Text+":"+ tb_客户端port.Text);

            System.Threading.Thread th= new System.Threading.Thread(new System.Threading.ThreadStart(客户端接收));                     //实例化线程
            th.Start();
            lb_client_status.Text = "已连接";
        }

        void 客户端接收()
        {
            while (true)
            {
                try
                {
                    byte[] Receivebytes = new byte[819200];
                    clientSocket.Receive(Receivebytes);                                                      //接受聊天数据
                    string serverMessage = Encoding.Default.GetString(Receivebytes);         //将字节序列解码成字符串
                    addmemo_client("接收："+ serverMessage.TrimEnd('\0'));                                    //获取文本
                }
                catch (Exception)
                {

                }
               
            }
        }

        private void btn_客户端断开_Click(object sender, EventArgs e)
        {
            clientSocket.Close();
            addmemo_client("断开与服务端的连接：" + tb_server_ip.Text + ":" + tb_客户端port.Text);
            lb_client_status.Text = "已断开";
        }

        private void button14_Click(object sender, EventArgs e)
        {
            config_server.server_port = tb_server_port.Text;
            config_server.指令1 = tb_指令1.Text;
            config_server.指令2 = tb_指令2.Text;
            config_server.指令3 = tb_指令3.Text;
            config_server.指令4 = tb_指令4.Text;
            config_server.指令5 = tb_指令5.Text;
            config_server.指令6 = tb_指令6.Text;
            config_server.指令7 = tb_指令7.Text;
            config_server.指令8 = tb_指令8.Text;
            config_server.指令9 = tb_指令9.Text;
            config_server.指令10 = tb_指令10.Text;
            config_server.用途1 = tb_用途1.Text;
            config_server.用途2 = tb_用途2.Text;
            config_server.用途3 = tb_用途3.Text;
            config_server.用途4 = tb_用途4.Text;
            config_server.用途5 = tb_用途5.Text;
            config_server.用途6 = tb_用途6.Text;
            config_server.用途7 = tb_用途7.Text;
            config_server.用途8 = tb_用途8.Text;
            config_server.用途9 = tb_用途9.Text;
            config_server.用途10 = tb_用途10.Text;
            Config_Json_Tcp_Server.save(config_server);
            MessageBox.Show("保存成功!");
        }
    }
}
